import React, { Component } from 'react';
import { connect } from 'react-redux';
import './index.scss'
import GobackHeader from '../../../../components/user/GobackHeader'
class Com extends Component {
	constructor(props){
		super(props)
		this.inputArr = []
		for(let i=0; i<6; i++){
			let a = 'ref' + i
			this.inputArr.push(a)
			// console.log(this.inputArr)
			this[a+''] = React.createRef()
		}
		this.flag = 0
	}
	componentDidMount(){
		this.ref0.current.focus()
	}
	checkNum(){
		//判断是否六个数都输入
		const checkFlagArr = []
		this.inputArr.forEach((item)=>{
			checkFlagArr.push(item)
		})
		const checkFlag =  checkFlagArr.every(item=>{
			return this[item].current.value !== ''
		})
		if(checkFlag) {
			alert('可以提交了')
			this.props.history.push('/user/newTel')
		}else{
			alert('请输入正确的验证码')
		}
	}
	numSingle(e,item,index){
		//解决按非数字键跳转问题
		if(isNaN(parseInt(this['ref' + (index)].current.value)) && e.keyCode !== 8){
			return true
		}
		// 判断是否连续两次按删除键
		if(e.keyCode === 8){
			this.flag +=1
			if(this.flag>2){
				this.flag = 1
			}
		}else{
			this.flag = 0
		}
		//确保只有一位
		this['ref' + (index)].current.value = this['ref' + (index)].current.value.slice(0,1)
		// 确保跳转焦点
		if(index === 5){
			if((this[item].current.value!=='')){
				console.log('提交')
			}
		}else if(e.keyCode!==8){
			console.log(e.keyCode)
			console.log('输入跳转')
			this['ref' + (index + 1)].current.focus()
		}
		//删除焦点跳转
		// console.log(e.keyCode)
		const myIndex = (index -1)<0?0:(index -1)
		console.log(this.flag)
		if(this['ref' + (index)].current.value ==='' && e.keyCode === 8 && this.flag ===2){
			this['ref' + myIndex].current.focus()
		}
	}
	render(){
		return (
			<>
				<div className="checkUser">
					<GobackHeader title='用户验证' />
					<p className='checkUser-tel'>
						<span>请输入验证码</span>
						<span>189****3465</span>
					</p>
					<div className="checkUser-num">
						{
							this.inputArr.map((item, index) => {
								return <input key={item+index} ref={this[item]} type="number" onKeyUp={(e)=>{this.numSingle(e,item,index)}} />
							})
						}
					</div>
					<div className="checkUser-send">
						发送验证码
					</div>
					<div onClick={()=>{this.checkNum()}} className="checkUser-next">
						下一步
					</div>
				</div>
			</>
		)
	}
}
export default connect()(Com)